<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Please login first']);
    exit;
}

// Check if car_id is provided
if (!isset($_POST['car_id'])) {
    echo json_encode(['success' => false, 'message' => 'Car ID is required']);
    exit;
}

$database = new Database();
$db = $database->getConnection();

$user_id = $_SESSION['user_id'];
$car_id = $_POST['car_id'];

try {
    // Check if favorite already exists
    $check_query = "SELECT id FROM favorites WHERE user_id = ? AND car_id = ?";
    $check_stmt = $db->prepare($check_query);
    $check_stmt->execute([$user_id, $car_id]);
    
    if ($check_stmt->rowCount() > 0) {
        // Remove favorite
        $delete_query = "DELETE FROM favorites WHERE user_id = ? AND car_id = ?";
        $delete_stmt = $db->prepare($delete_query);
        $delete_stmt->execute([$user_id, $car_id]);
        echo json_encode(['success' => true, 'action' => 'removed']);
    } else {
        // Add favorite
        $insert_query = "INSERT INTO favorites (user_id, car_id) VALUES (?, ?)";
        $insert_stmt = $db->prepare($insert_query);
        $insert_stmt->execute([$user_id, $car_id]);
        echo json_encode(['success' => true, 'action' => 'added']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
?> 